package com.nf.health.app.activity.global;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.models.AJAXLogin;
import com.nf.health.app.models.OrderLogin;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.AppManager;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.widget.datePicker.MyWheelView;
import com.nf.health.app.widget.datePicker.OnWheelScrollListener;
import com.nf.health.app.widget.datePicker.adapter.NumericWheelAdapter;

import java.util.Calendar;

/**
 * @author Ian
 * @ClassName: RegisterBirthdayActivity
 * @Description: 注册 生日
 * @date 2015-11-4 上午11:01:48
 */
public class RegisterBirthdayActivity extends BaseActivity {


    int gender;

    OrderLogin orderLogin;

    private Button next_btn;
    private String sex;
    private ImageView sex_img;
    private TextView titlebar_title_tv;
    private String nick_name;
    private String height;
    private String weight;
    public static String orderToken;
    private String password;
    private String type = "";
    private String birthday = "";
    private int year;
    private int monthOfYear;
    private int dayOfMonth;
    private Context context;
    private LayoutInflater inflater = null;
    /********************
     * 对日期进行处理
     **************/
    private View view;
    private LinearLayout ll_mywhell;//存放日期轮子的LinearLayout
    private com.nf.health.app.widget.datePicker.MyWheelView whYear;
    private com.nf.health.app.widget.datePicker.MyWheelView whMonth;
    private com.nf.health.app.widget.datePicker.MyWheelView whDay;
    private int currentYear = 1946;
    private int currentMonth = 0;
    private int currentDay = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getStringExtra("type");
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_register_birthday);
        context = RegisterBirthdayActivity.this;
        initView();
    }

    @SuppressLint("NewApi")
    public void initView() {
        inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        titlebar_title_tv = (TextView) this.findViewById(R.id.titlebar_title_tv);
        ll_mywhell = (LinearLayout) this.findViewById(R.id.ll_mywhell);
        titlebar_title_tv.setText("生日");
        sex_img = (ImageView) this.findViewById(R.id.sex_img);
        ll_mywhell.addView(initDateViews());
        if ("1".equals(type)) {//是过来修改的时候
            birthday = PreferenceHelper.getString(PreferenceHelper.BIRTHDAY, "1900-01-01");
            sex = PreferenceHelper.getString(PreferenceHelper.USERSEX, "1");
        } else {
            sex = getIntent().getStringExtra("sex");
            nick_name = getIntent().getStringExtra("nick_name");
            height = getIntent().getStringExtra("height");
            weight = getIntent().getStringExtra("weight");
        }
        if ("1".equals(sex)) {
            sex_img.setBackgroundResource(R.drawable.ka2);
        } else {
            sex_img.setBackgroundResource(R.drawable.ka);
        }
        next_btn = (Button) this.findViewById(R.id.next_btn);
        if ("1".equals(type)) {
            next_btn.setText("确定");
        }
        if ("3".equals(type)) {
            next_btn.setText("确定");
        }
        next_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if ("1".equals(type)) {
                    provider.requestUpdateUser(null, null, birthday, null, null, null, null, null,null,"updataUser");
                } else if ("3".equals(type)) {
                    provider.requestUpdateUser(nick_name, sex, birthday, weight, height, null, null, null,null, "updateUser");
                } else {
//					provider.requestRegisterInfo(nick_name, sex, birthday, weight, height, "RegisterInfo");
                    provider.requestUpdateUser(nick_name, sex, birthday, weight, height, null, null, null,null, "RegisterInfo");
                }
            }
        });

        //设置当前的日期:
        //DatePicker datePicker=(DatePicker)findViewById(R.id.datePicker);
        if (TextUtils.isEmpty(birthday)) {
//            Calendar calendar = Calendar.getInstance();
            year =1967;
            monthOfYear = 1;
            dayOfMonth = 5;

            birthday = year + "-" + monthOfYear + "-" + dayOfMonth;//控件默认值
            /**
             * 这是由于登录之后，birthday是在登录的时候保存的，登录去完善个人资料，没有再次保存，固添加此代码
             */
            PreferenceHelper.putString(PreferenceHelper.BIRTHDAY, birthday);
        } else {
            String[] datas = birthday.split("-");
            try {
                year = Integer.parseInt(datas[0]);
                monthOfYear = Integer.parseInt(datas[1]);
                dayOfMonth = Integer.parseInt(datas[2]);
            } catch (Exception e) {
            }
        }
        setUserBirthday(year, monthOfYear, dayOfMonth);
        /*datePicker.setMaxDate(System.currentTimeMillis());
		datePicker.init(year, monthOfYear, dayOfMonth, new OnDateChangedListener() {

			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				birthday = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
			}
		});*/

    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (actionName.equals("updateUserAgain")) {
            AppManager.getAppManager().finishAllActivity();
            ActivityUtils.skipActivity(this, MainActivity.class);
        } else if (actionName.equals("updataUser")) {
            PreferenceHelper.putString(PreferenceHelper.BIRTHDAY, birthday);
            showToast("修改成功！");
            finish();
        } else if (actionName.equals("updateUser")) {
            AppManager.getAppManager().finishAllActivity();
            ActivityUtils.showActivity(this, MainActivity.class);

        } else if (actionName.equals("RegisterInfo")) {
            AppManager.getAppManager().finishAllActivity();
            ActivityUtils.showActivity(this, LoginActivity.class);
            PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
            //是否完善了注册信息
            PreferenceHelper.putBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE,true);
//			orderLogin = (OrderLogin) object;
//			password = orderLogin.getPassword();
//			PreferenceHelper.putString(PreferenceHelper.ORDER_TOKEN,orderLogin.getToken());
//			PreferenceHelper.putString(PreferenceHelper.USERNICK, nick_name);
//			PreferenceHelper.putString(PreferenceHelper.USERSEX,sex);
//			PreferenceHelper.putString(PreferenceHelper.USERHEIGHT,height);
//			PreferenceHelper.putString(PreferenceHelper.BIRTHDAY,birthday);
//			PreferenceHelper.putString(PreferenceHelper.USERWEIGHT, weight);
//			//TODO 清理注册页面
//			PreferenceHelper.putBoolean("IS_FIRST_TIME", true);
//			PreferenceHelper.putBoolean("IS_FIRST_TIME_USE", true);
//			ActivityUtils.showActivity(RegisterBirthdayActivity.this,LoginActivity.class);
        } else if ("requestLogin".equals(actionName)) {
            AJAXLogin ajaxLogin = (AJAXLogin) object;
            PreferenceHelper.putString(PreferenceHelper.TOKEN, ajaxLogin.getCode());
            PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, true);
            provider.requestUpdateUser(nick_name, sex, birthday, weight, height, null, null, null,null, "updateUser");
            provider.requestUserInfo("userInfo");
        }
        //			JPushInterface.setAliasAndTags(getApplicationContext(), userInfo.getUserid(), null, mAliasCallback);
    }

    public static String encode(String code) {
        if (TextUtils.isEmpty(code)) {
            return "";
        }
        StringBuffer rs = new StringBuffer("");
        for (int i = 0; i < code.length(); i++) {
            rs.append("$").append((int) code.charAt(i)).append("1").append(";");
        }
        return new String(rs);
    }

    /********************
     * 对日期进行处理
     **************/
    private View initDateViews() {
        view = inflater.inflate(R.layout.wheel_date_picker, null);//获取布局，开始初始化
        Calendar c = Calendar.getInstance();
        int norYear = c.get(Calendar.YEAR);
        int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        int curDate = c.get(Calendar.DATE);

        currentYear = norYear;
        curMonth = curMonth + 1;
        currentDay = curDate;
        whYear = (MyWheelView) view.findViewById(R.id.year);
        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(context, 1900, Calendar.getInstance().get(Calendar.YEAR));
        numericWheelAdapter1.setLabel("年");
        whYear.setViewAdapter(numericWheelAdapter1);
        whYear.setCyclic(true);//是否可循环滑动
        whYear.addScrollingListener(scrollListener);

        whMonth = (MyWheelView) view.findViewById(R.id.month);
        NumericWheelAdapter numericWheelAdapter2 = new NumericWheelAdapter(context, 1, 12, "%02d");
        numericWheelAdapter2.setLabel("月");
        whMonth.setViewAdapter(numericWheelAdapter2);
        whMonth.setCyclic(true);
        whMonth.addScrollingListener(scrollListener);

        whDay = (MyWheelView) view.findViewById(R.id.day);
        initDay(currentYear, curMonth);
        whDay.setCyclic(true);
        whDay.addScrollingListener(scrollListener);


        whYear.setVisibleItems(4);//设置显示行数
        whMonth.setVisibleItems(4);
        whDay.setVisibleItems(4);
        whYear.setCurrentItem(currentYear - 1900);
        whMonth.setCurrentItem(curMonth - 1);
        whDay.setCurrentItem(curDate - 1);
        return view;
    }

    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
        @Override
        public void onScrollingStarted(MyWheelView wheel) {

        }

        @Override
        public void onScrollingFinished(MyWheelView wheel) {
            int n_year = whYear.getCurrentItem() + 1900;//年
            int n_month = whMonth.getCurrentItem() + 1;//月

            initDay(n_year, n_month);
            //System.out.print(whYear.getCurrentItem() + "-----" + whMonth.getCurrentItem() + "------" + whDay.getCurrentItem());
            //LogUtil.d("yuyahao",whYear.getCurrentItem() + "-----" + whMonth.getCurrentItem() + "------" + whDay.getCurrentItem());
            String syear = (whYear.getCurrentItem() + 1900) + "";
            String sMonth = ((whMonth.getCurrentItem() + 1) < 10 ? "0" + (whMonth.getCurrentItem() + 1) : (whMonth.getCurrentItem() + 1)).toString();
            String sday = (((whDay.getCurrentItem() + 1) < 10) ? "0" + (whDay.getCurrentItem() + 1) : (whDay.getCurrentItem() + 1)).toString();
            birthday = syear + "-" + sMonth + "-" + sday;
        }
    };

    /**
     * @param year
     * @param month
     * @return
     */
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }

    /**
     */
    private void initDay(int arg1, int arg2) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(context, 1, getDay(arg1, arg2), "%02d");
        numericWheelAdapter.setLabel("日");
        whDay.setViewAdapter(numericWheelAdapter);
    }

    /******************/
    private void setUserBirthday(int cYear, int cMonth, int cDay) {
        whYear.setCurrentItem(cYear - 1900);//所减去的这个值要和传入的这个年份要保持一致
        whMonth.setCurrentItem(cMonth-1);
        whDay.setCurrentItem(cDay - 1);
    }
}
